package com.xiaoxing.controller;

import com.xiaoxing.annotation.SystemLog;
import com.xiaoxing.domain.ResponseResult;
import com.xiaoxing.domain.dto.UserDto;
import com.xiaoxing.domain.entity.User;
import com.xiaoxing.enums.AppHttpCodeEnum;
import com.xiaoxing.service.UserService;
import com.xiaoxing.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("用户信息")
    @GetMapping("/userInfo")
    public ResponseResult userInfo(){
        return userService.userInfo();
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/userInfo")
    @SystemLog(businessName = "更新用户信息")
    public ResponseResult updateUserInfo(@RequestBody User user){
        return userService.updateUserInfo(user);
    }


    @ApiOperation("注册用户")
    @PostMapping("/register")
    public ResponseResult register(@RequestBody User user){
        return userService.register(user);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/changeUserPassword")
    @SystemLog(businessName = "修改用户密码")
    public ResponseResult changeUserPassword(@RequestBody UserDto user){
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user1 = userService.getById(userId);
        //对密码进行加密
        if (!user.getOldPassword().equals(user1.getPassSave())){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANGE_ERR);
        }else{
            user1.setPassword(passwordEncoder.encode(user.getNewPassword()));
            user1.setPassSave(user.getNewPassword());
        }
        return userService.updateUserInfo(user1);
    }
}
